package vn.ugame.model.dal;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import vn.ugame.exception.DataConnectionFailed;
import vn.ugame.exception.InvalidEntityClass;
import vn.ugame.model.entity.Config;

public class ConfigDA {
    
    public Config findConfig(Locale locale, String key) 
            throws DataConnectionFailed, SQLException, InvalidEntityClass {
        if (locale != null && key != null) {
            List<Config> configs = findConfigs(locale, key);
            if (configs.size() > 0) {
                return configs.get(0);
            }
        }        
        return null;
    }
    
    public List<Config> findConfigs(Locale locale, String key) 
            throws DataConnectionFailed, SQLException, InvalidEntityClass {
        
        List<Config> configList = new ArrayList<Config>();
        
        Connection conn = ConnectionFactory.getInstance().createDBConnection();
        
        String query = "{ call findConfigs(?,?) }";
        CallableStatement cs = conn.prepareCall(query);
        if (locale == null) {
            cs.setNull(1, Types.VARCHAR);
        } else {
            cs.setString(1, locale.getLanguage());
        }
        cs.setString(2, key);
        
        ResultSet rs = cs.executeQuery();
        EntityFactory factory = EntityFactory.createEntityFactory();
        while (rs.next()) {
            Config config = factory.createEntity(rs, Config.class);
            configList.add(config);
        }
        rs.close();
        cs.close();
        conn.close();
        return configList;
    }
}
